package org.f0rb.demo.web;

import org.f0rb.core.web.WebContext;
import org.f0rb.demo.common.Message;
import org.f0rb.demo.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description goes here.
 *
 * @author yuanzhen
 * @version 1.0, 2012-02-09
 */
public class WebContextFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(WebContextFilter.class);

    private static final String DEFAULT_LOCALE_NAME = "html_locale";

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if (!request.getRequestURI().contains(".")) {
            WebContext.setRequest(request);
            WebContext.setResponse(response);

            setLocale(request);
        }
        chain.doFilter(req, res);
    }

    public void destroy() {
    }

    private void setLocale(HttpServletRequest request) {
        // 先从参数中取locale, 若没有, 从cookie中取, 若仍没有, 取浏览器的默认值
        Object locale = request.getAttribute(DEFAULT_LOCALE_NAME);
        if (locale == null) {
            Cookie localeCookie = RequestUtils.getCookie(request, DEFAULT_LOCALE_NAME);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Request Locale : {}", locale);
                if (localeCookie != null) {
                    LOGGER.debug("Cookie Locale  : {}", localeCookie.getValue());
                }
                LOGGER.debug("Browser Locale : {}", request.getLocale().toLanguageTag());
            }
            locale = localeCookie != null ? localeCookie.getValue() : request.getLocale();
        }
        LOGGER.info("Message.setLocale({})", locale);
        Message.setLocale(locale);
    }
}
